<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>健康记录管理</h2>
          <el-button
              type="primary"
              icon="el-icon-plus"
              @click="showFormDialog = true"
          >
            新增记录
          </el-button>
        </div>
      </template>

      <!-- 健康记录表格 -->
      <el-table
          :data="recordList"
          v-loading="loading"
          border
          stripe
          style="width: 100%"
      >
        <el-table-column
            prop="createTime"
            label="记录时间"
            width="180"
            sortable
        ></el-table-column>
        
        <el-table-column
            prop="elderName"
            label="老人姓名"
            width="120"
        ></el-table-column>
        
        <el-table-column
            prop="bloodPressure"
            label="血压(mmHg)"
            width="150"
        ></el-table-column>
        
        <el-table-column
            prop="heartRate"
            label="心率(bpm)"
            width="120"
        ></el-table-column>
        
        <el-table-column
            prop="bloodSugar"
            label="血糖(mmol/L)"
            width="150"
        ></el-table-column>
        
        <el-table-column
            label="医生建议"
        >
          <template #default="{row}">
            <div style="white-space: pre-wrap;">{{ row.doctorSuggestions || '-' }}</div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
          class="pagination"
          :current-page="pageInfo.pageNum"
          :page-sizes="[5, 10, 20]"
          :page-size="pageInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      ></el-pagination>

      <!-- 新增记录弹窗 -->
      <el-dialog
          title="新增健康记录"
          v-model="showFormDialog"
          width="600px"
          @closed="resetForm"
      >
        <el-form
            :model="form"
            label-width="120px"
        >
          <el-form-item label="老人姓名" required>
            <el-select v-model="form.elderId" placeholder="请选择老人">
              <el-option
                  v-for="elder in elderList"
                  :key="elder.id"
                  :label="elder.nickname"
                  :value="elder.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="血压(mmHg)" required>
            <el-input v-model="form.bloodPressure" placeholder="格式：收缩压/舒张压"></el-input>
          </el-form-item>

          <el-form-item label="心率(bpm)" required>
            <el-input v-model="form.heartRate"></el-input>
          </el-form-item>

          <el-form-item label="血糖(mmol/L)">
            <el-input v-model="form.bloodSugar"></el-input>
          </el-form-item>

          <el-form-item label="医生建议">
            <el-input type="textarea" v-model="form.doctorSuggestions"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submit">提交记录</el-button>
            <el-button @click="showFormDialog = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import http from '@/utils/http.js'
import utils from "@/utils/tools.js";

const showFormDialog = ref(false)
const recordList = ref([])
const elderList = ref([])
const pageInfo = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

const form = ref({
  elderId: '',
  bloodPressure: '',
  heartRate: '',
  bloodSugar: '',
  doctorSuggestions: ''
})

const loading = ref(false)

onMounted(async () => {
  await getElderList()
  await getHealthRecords()
})

async function getElderList() {
  try {
    const staff = await http.get(`/staff/selectById/${utils.getCurrentUser().id}`)
    if (staff.data) {
      const buildingId = staff.data.buildingId
      const res = await http.get(`/elder/selectByBuildingId/${buildingId}`)
      elderList.value = res.data
    }
  } catch (e) {
    if (e.response?.status !== 404) {
      ElMessage.error('获取老人列表失败')
    }
  }
}

async function getHealthRecords() {
  loading.value = true
  try {
    const res = await http.get('/health_record/page', {
      params: {
        staffId: utils.getCurrentUser().id,
        pageNum: pageInfo.value.pageNum,
        pageSize: pageInfo.value.pageSize
      }
    })
    recordList.value = res.data.list.map(item => ({
      ...item,
      elderName: elderList.value.find(e => e.id === item.elderId)?.nickname || '未知'
    }))
    pageInfo.value.total = res.data.total
  } catch (e) {
    ElMessage.error('获取健康记录失败')
  } finally {
    loading.value = false
  }
}

const submit = () => {
  try {
    http.post('/health_record/add', {
      ...form.value,
      staffId: utils.getCurrentUser().id
    }).then(() => {
      ElMessage.success('记录提交成功')
      getHealthRecords()
      showFormDialog.value = false
      form.value = {
        elderId: '',
        bloodPressure: '',
        heartRate: '',
        bloodSugar: '',
        doctorSuggestions: ''
      }
    })
  } catch (e) {
    ElMessage.error('记录提交失败')
  }
}

const handleSizeChange = (val) => {
  pageInfo.value.pageSize = val
  getHealthRecords()
}

const handleCurrentChange = (val) => {
  pageInfo.value.pageNum = val
  getHealthRecords()
}

const resetForm = () => {
  form.value = {
    elderId: '',
    bloodPressure: '',
    heartRate: '',
    bloodSugar: '',
    doctorSuggestions: ''
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style> 